<template>
  <div class="login">
    <van-nav-bar title="登录"></van-nav-bar>
    <div class="main">
      <van-form ref="form">
        <van-field
          label="手机号"
          placeholder="请输入用户名"
          v-model="form.mobile"
          :rules="rules.mobile"
        ></van-field>
        <van-field
          placeholder="请输入验证码"
          label="验证码"
          v-model="form.code"
          :rules="rules.code"
        ></van-field>
      </van-form>
      <van-button :loading="loading" type="info" @click="submit" block round>
        登录
      </van-button>
    </div>
  </div>
</template>

<script>
import { authorizations } from '@/api/user.js'

export default {
  data () {
    return {
      loading: false,
      form: {
        mobile: '',
        code: '246810'
      },
      rules: {
        mobile: [
          { required: true, message: '必填', trigger: 'onBlur' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'onBlur'
          }
        ],
        code: [
          { required: true, message: '必填', trigger: 'onBlur' },
          {
            pattern: /^\d{6}$/,
            message: '请输入正确的验证码',
            trigger: 'onBlur'
          }
        ]
      }
    }
  },
  methods: {
    async submit () {
      this.$refs.form
        .validate()
        .then(async () => {
          this.loading = true
          try {
            const res = await authorizations(this.form)
            this.loading = false
            this.$toast.success('登录成功')
            this.$store.commit('setTokenObj', res.data.data)
            const back = this.$route.query.back
            this.$router.push(back || '/layout/home')
          } catch (error) {
            this.loading = false
          }
        })
        .catch(() => {
        })
    }
  }
}
</script>

<style lang="less" scoped>
.main {
  padding: 0 20px;
  .van-field {
    margin: 20px 10px;
  }
}
</style>
